package com.coocaa.x.service.litecache.data.common;

import java.lang.Thread.UncaughtExceptionHandler;
import java.util.UUID;

import android.os.Handler;
import android.os.Looper;
import android.os.RemoteException;

import com.coocaa.x.framework.data.JObject;
import com.coocaa.x.service.XServiceManager;
import com.coocaa.x.service.litecache.aidl.ILiteCacheCachingListener;
import com.coocaa.x.service.litecache.aidl.ILiteCacheLockingListener;

/**
 * Created by lu on 15-3-13.
 */
public class LiteCacheObject extends JObject implements Cloneable {
    private static Handler handler = null;

    static {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                handler = new Handler(Looper.myLooper());
                Looper.loop();
            }
        }, "LiteCacheThread").start();
    }

    // private static ThreadPoolExecutor executor = null;
    //
    // static
    // {
    // executor = new ThreadPoolExecutor(3, 3, 10, TimeUnit.DAYS,
    // new LinkedBlockingQueue<Runnable>(), new ThreadFactory()
    // {
    // @Override public Thread newThread(Runnable r)
    // {
    // Thread thread = new Thread(r, "LiteCacheClient");
    // thread.setUncaughtExceptionHandler(uncaughtExceptionHandler);
    // return thread;
    // }
    // });
    // // executor.prestartAllCoreThreads();
    // }

    private static final UncaughtExceptionHandler uncaughtExceptionHandler = new UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread thread, Throwable ex) {
            // ex.printStackTrace();
        }
    };

    public static void postAction(Runnable run) {
        // executor.execute(run);
        while (handler == null)
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                // e.printStackTrace();
            }
        handler.post(run);
    }

    public static void cache(final String url, final LiteCacheObjectCacheListener l)
            throws Exception {
        postAction(new Runnable() {
            @Override
            public void run() {
                try {
                    XServiceManager.getLiteCacheService().cache(url,
                            new ILiteCacheCachingListener.Stub() {
                                @Override
                                public void onLiteCacheObjectCached(String jsonObj,
                                                                    boolean success, String failmsg, String extra)
                                        throws RemoteException {
                                    l.onLiteCacheObjectCached(success, LiteCacheObject
                                            .parseJObject(jsonObj, LiteCacheObject.class));
                                }
                            });
                } catch (RemoteException e) {
                    // e.printStackTrace();
                }
            }
        });
    }

    public static interface LiteCacheObjectCacheListener {
        void onLiteCacheObjectCached(boolean success, LiteCacheObject obj);
    }

    public static interface LiteCacheObjectLockListener {
        void onLiteCacheObjectLocked(LiteCacheObject obj, boolean success, String content);
    }

    public String id = UUID.randomUUID().toString();
    public String url = null;

    public LiteCacheObject() {

    }

    public LiteCacheObject(String url) {
        this.url = url;
    }

    public void lock(final LiteCacheObjectLockListener l) throws Exception {
        postAction(new Runnable() {
            @Override
            public void run() {
                try {
                    String json = toJSONString();
                    XServiceManager.getLiteCacheService().lock(json,
                            new ILiteCacheLockingListener.Stub() {
                                @Override
                                public void onLiteCacheObjectLocked(String jsonObj,
                                                                    boolean success, String failmsg, String content)
                                        throws RemoteException {
                                    l.onLiteCacheObjectLocked(LiteCacheObject.this, success,
                                            content);
                                }
                            });
                } catch (RemoteException e) {
                    // e.printStackTrace();
                }
            }
        });
    }

    public void unlock() throws Exception {
        try {
            String json = toJSONString();
            XServiceManager.getLiteCacheService().unlock(json);
        } catch (RemoteException e) {
            // e.printStackTrace();
        }
    }

    public final Object clone() {
        LiteCacheObject obj = null;
        try {
            obj = (LiteCacheObject) super.clone();
            obj.id = UUID.randomUUID().toString();
        } catch (CloneNotSupportedException e) {
            // e.printStackTrace();
        }
        return obj;
    }

    @Override
    public final boolean equals(Object o) {
        try {
            return id.equals(((LiteCacheObject) o).id);
        } catch (Exception e) {
        }
        return false;
    }
}
